//
//  DYCameraViewController.m
//  colorTest
//
//  Created by 丁益 on 2017/4/2.
//  Copyright © 2017年 celi. All rights reserved.
//  相机取色

#import <QuartzCore/QuartzCore.h>
#import "DYCameraViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "DYColorView.h"
#import "AsyncUdpSocket.h"

@interface DYCameraViewController ()<AVCaptureMetadataOutputObjectsDelegate,UIAlertViewDelegate>
{
    NSTimer *refreshScreenTimer;
}

//捕获设备，通常是前置摄像头，后置摄像头，麦克风（音频输入）
@property(nonatomic)AVCaptureDevice *device;

//AVCaptureDeviceInput 代表输入设备，他使用AVCaptureDevice 来初始化
@property(nonatomic)AVCaptureDeviceInput *input;

//当启动摄像头开始捕获输入
@property(nonatomic)AVCaptureMetadataOutput *output;

@property (nonatomic)AVCaptureStillImageOutput *ImageOutPut;

//session：由他把输入输出结合在一起，并开始启动捕获设备（摄像头）
@property(nonatomic)AVCaptureSession *session;

//图像预览层，实时显示捕获的图像
@property(nonatomic)AVCaptureVideoPreviewLayer *previewLayer;

@property (nonatomic)UIButton *PhotoButton;
@property (nonatomic)UIButton *flashButton;
@property (nonatomic)UIImage *image;

@property (nonatomic, weak) DYColorView *colorView;
@property (nonatomic, weak) UILabel *showColor;

@property (nonatomic)BOOL canCa;
@property (nonatomic,assign) bool isAuto;
@property (nonatomic, weak) UIImageView *aimPointImageView;
@end

@implementation DYCameraViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"相机取色";
    UIButton *leftBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 30, 30)];
    
    UIBarButtonItem *leftBarItem = [[UIBarButtonItem alloc]initWithCustomView:leftBtn];
    
    self.navigationItem.leftBarButtonItem = leftBarItem;
    
    _canCa = [self canUserCamear];
    if (_canCa) {
        [self customCamera];
        [self customUI];
    }else{
        return;
    }
    
    [self creatTimer];
    [self creatAutoSelectSegmented];
    
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [self stopTimer];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc
{
    refreshScreenTimer = nil;
}


- (void)creatAutoSelectSegmented
{
    NSArray *arr = [[NSArray alloc]initWithObjects:@"手动",@"自动", nil];
    //先创建一个数组用于设置标题
    
    UISegmentedControl *segment = [[UISegmentedControl alloc]initWithItems:arr];
    //在没有设置[segment setApportionsSegmentWidthsByContent:YES]时，每个的宽度按segment的宽度平分
    segment.frame = CGRectMake(0, 84, 100, 40);
    [segment setSelectedSegmentIndex:0];
    segment.centerX = sWidth/2;
    [segment addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged];
    
    [self.view addSubview:segment];
    
}

- (void)segmentAction:(UISegmentedControl *)Seg
{
    NSInteger Index = Seg.selectedSegmentIndex;
    
    switch (Index) {
        case 0:
            [self stopTimer];
            self.isAuto = NO;
            break;
        case 1:
            [self startTimer];
            self.isAuto = YES;
            break;
        default:
            
            break;
    }
}

//获取图片某一点的颜色
- (UIColor *)colorAtPixel:(CGPoint)point image:(UIImage*)image {
    
    if (!CGRectContainsPoint(CGRectMake(0.0f, 0.0f, image.size.width, image.size.height), point)) {
        return nil;
    }
    
    NSInteger pointX = trunc(point.x);
    NSInteger pointY = trunc(point.y);
    CGImageRef cgImage = image.CGImage;
    NSUInteger width = image.size.width;
    NSUInteger height = image.size.height;
   
    DLog(@"pointX=%lu pointY=%lu",(unsigned long)pointX,(unsigned long)pointY);
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    int bytesPerPixel = 4;
    int bytesPerRow = bytesPerPixel * 1;
    NSUInteger bitsPerComponent = 8;
    unsigned char pixelData[4] = { 0, 0, 0, 0 };
    CGContextRef context = CGBitmapContextCreate(pixelData,
                                                 1,
                                                 1,
                                                 bitsPerComponent,
                                                 bytesPerRow,
                                                 colorSpace,
                                                 kCGImageAlphaPremultipliedLast |     kCGBitmapByteOrder32Big);
    CGColorSpaceRelease(colorSpace);
    CGContextSetBlendMode(context, kCGBlendModeCopy);
    

//    CGContextTranslateCTM(context, -pointX, pointY-(CGFloat)height);
    CGContextTranslateCTM(context, -(width/2.0), -(height/2.0));
    CGContextDrawImage(context, CGRectMake(0.0f, 0.0f, (CGFloat)width, (CGFloat)height), cgImage);
    CGContextRelease(context);
    
    CGFloat red   = (CGFloat)pixelData[0] ;/// 255.0f;
    CGFloat green = (CGFloat)pixelData[1] ;/// 255.0f;
    CGFloat blue  = (CGFloat)pixelData[2] ;/// 255.0f;
    CGFloat alpha = (CGFloat)pixelData[3] / 255.0f;
    
    DLog(@"red =%f green = %f blue =%f", red,green,blue);
    [self.colorView setRedValue:[NSString stringWithFormat:@"%0.0f",red] greenValue:[NSString stringWithFormat:@"%0.0f",green] blueValue:[NSString stringWithFormat:@"%0.0f",blue]];
    self.showColor.backgroundColor = DYColor(red, green, blue);
    
    //发送数据
    [self sendCameraDataWithRedValue:[NSString stringWithFormat:@"%0.0f",red] greenValue:[NSString stringWithFormat:@"%0.0f",green]  blueValue:[NSString stringWithFormat:@"%0.0f",blue]];
    return [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
}



// 采集颜色
- (void)catchColorDowm
{
//    [self stopTimer];
    DLog(@"catchColor---");
    [self startTimer];
}

//停止采集颜色
- (void)catchColorUpInside
{
    [self stopTimer];
    DLog(@"catchColorUpInside---");
}

#pragma mark - 截取照片
- (void) shutterCamera
{
    AVCaptureConnection * videoConnection = [self.ImageOutPut connectionWithMediaType:AVMediaTypeVideo];
    if (!videoConnection) {
        NSLog(@"take photo failed!");
        return;
    }
    
    [self.ImageOutPut captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) {
        if (imageDataSampleBuffer == NULL) {
            return;
        }
        NSData * imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
        self.image = [UIImage imageWithData:imageData];
        //[self.session stopRunning];
        //[self saveImageToPhotoAlbum:self.image];
        [self colorAtPixel:CGPointMake(sWidth/2, sHeight/2) image:self.image];
        
        NSLog(@"image size = %@",NSStringFromCGSize(self.image.size));
    }];
}
#pragma - 保存至相册
- (void)saveImageToPhotoAlbum:(UIImage*)savedImage
{
    UIImageWriteToSavedPhotosAlbum(savedImage, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
}

// 指定回调方法
- (void)image: (UIImage *) image didFinishSavingWithError: (NSError *) error contextInfo: (void *) contextInfo
{
    NSString *msg = nil ;
    if(error != NULL){
        msg = @"保存图片失败" ;
    }else{
        msg = @"保存图片成功" ;
    }
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"保存图片结果提示"
                                                    message:msg
                                                   delegate:self
                                          cancelButtonTitle:@"确定"
                                          otherButtonTitles:nil];
    [alert show];
}

#pragma mark -定时器
- (void)stopTimer
{
    //关闭定时器
    [refreshScreenTimer setFireDate:[NSDate distantFuture]];
}


- (void)startTimer
{
    //开启定时器
    [refreshScreenTimer setFireDate:[NSDate distantPast]];
}

- (void)creatTimer
{
    if ([refreshScreenTimer isValid]) {
        [refreshScreenTimer invalidate];
    }
    refreshScreenTimer = [NSTimer scheduledTimerWithTimeInterval:0.3 target:self selector:@selector(willRefreshScreen) userInfo:nil repeats:YES];
    [self stopTimer];
}


- (void)willRefreshScreen
{
    
    [self shutterCamera];
}


#pragma mark - 相机自定义
- (void)customCamera {
    self.view.backgroundColor = [UIColor whiteColor];
    
    //使用AVMediaTypeVideo 指明self.device代表视频，默认使用后置摄像头进行初始化
    self.device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    //使用设备初始化输入
    self.input = [[AVCaptureDeviceInput alloc]initWithDevice:self.device error:nil];
    
    //生成输出对象
    self.output = [[AVCaptureMetadataOutput alloc]init];
    self.ImageOutPut = [[AVCaptureStillImageOutput alloc] init];
    
    //生成会话，用来结合输入输出
    self.session = [[AVCaptureSession alloc]init];
    if ([self.session canSetSessionPreset:AVCaptureSessionPreset1280x720]) {
        
        self.session.sessionPreset = AVCaptureSessionPreset1280x720;
        
    }
    if ([self.session canAddInput:self.input]) {
        [self.session addInput:self.input];
    }
    
    if ([self.session canAddOutput:self.ImageOutPut]) {
        [self.session addOutput:self.ImageOutPut];
    }
    
    //使用self.session，初始化预览层，self.session负责驱动input进行信息的采集，layer负责把图像渲染显示
    self.previewLayer = [[AVCaptureVideoPreviewLayer alloc]initWithSession:self.session];
    self.previewLayer.frame = CGRectMake(0, 0, sWidth, sHeight);
    self.previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    [self.view.layer addSublayer:self.previewLayer];
    
    //开始启动
    [self.session startRunning];
    if ([_device lockForConfiguration:nil]) {
        if ([_device isFlashModeSupported:AVCaptureFlashModeAuto]) {
            [_device setFlashMode:AVCaptureFlashModeAuto];
        }
        //自动白平衡
        if ([_device isWhiteBalanceModeSupported:AVCaptureWhiteBalanceModeAutoWhiteBalance]) {
            [_device setWhiteBalanceMode:AVCaptureWhiteBalanceModeAutoWhiteBalance];
        }
        [_device unlockForConfiguration];
    }
}

- (void)customUI {
    _PhotoButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _PhotoButton.frame = CGRectMake(sWidth*1/2.0-25, sHeight-120, 50, 50);
    [_PhotoButton setImage:[UIImage imageNamed:@"photograph"] forState: UIControlStateNormal];
    [_PhotoButton setImage:[UIImage imageNamed:@"photograph_Select"] forState:UIControlStateNormal];
    [_PhotoButton addTarget:self action:@selector(catchColorDowm) forControlEvents:UIControlEventTouchDown];
    [_PhotoButton addTarget:self action:@selector(catchColorUpInside) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:_PhotoButton];
    
//    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(btnLong:)];
//    longPress.minimumPressDuration = 0.8; //定义按的时间
//    [_PhotoButton addGestureRecognizer:longPress];
    
    CGFloat showColorX = 10;
    CGFloat showColorY = 84;
    
    UILabel *showColor = [[UILabel alloc]initWithFrame:CGRectMake(showColorX, showColorY, 36, 36)];
    showColor.layer.cornerRadius = 4;
    showColor.layer.masksToBounds = YES;
    showColor.backgroundColor = [UIColor whiteColor];
    showColor.layer.borderColor = [UIColor lightGrayColor].CGColor;
    showColor.layer.borderWidth = 1;
    //showColor.layer.shadowColor = [UIColor grayColor].CGColor;
    self.showColor = showColor;
    [self.view addSubview:showColor];
    
    CGFloat colorViewX = showColor.x;
    CGFloat colorViewY = CGRectGetMaxY(showColor.frame)+5;
    DYColorView *colorView = [DYColorView colorViewWithFream:CGRectMake(colorViewX, colorViewY, 45, 60) RedValue:[NSString stringWithFormat:@"%0.0f",255.0]  blueValue:[NSString stringWithFormat:@"%0.0f",255.0]  greenValue:[NSString stringWithFormat:@"%0.0f",255.0] addTarget:self action:@selector(labelOnclick:)];
    self.colorView = colorView;
    [self.view addSubview:colorView];
    
    
    //添加取色瞄准点
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
    imageView.image = [UIImage imageNamed:@"img_addscene"];
    imageView.centerX = sWidth/2;
    imageView.centerY = sHeight/2;
//    [imageView setBackgroundColor:[UIColor redColor]];
    self.aimPointImageView = imageView;
    [self.view addSubview:imageView];
    
}

- (void)btnLong:(UILongPressGestureRecognizer *)gestureRecognizer {
    DLog(@"long ----- tap");
    [self startTimer];
}

- (void)labelOnclick:(DYColorView *)colorView
{
    DLog(@"labelOnclick---");
}


#pragma mark - 检查相机权限
- (BOOL)canUserCamear {
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusDenied) {
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"请打开相机权限" message:@"设置-隐私-相机" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
        alertView.tag = 100;
        [alertView show];
        return NO;
    }
    else{
        return YES;
    }
    return YES;
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0 && alertView.tag == 100) {
        
        NSURL * url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        
        if([[UIApplication sharedApplication] canOpenURL:url]) {
            
            [[UIApplication sharedApplication] openURL:url];
            
        }
    }
}


- (void)sendCameraDataWithRedValue:(NSString*)redValue greenValue:(NSString*)greenValue blueValue:(NSString*)blueValue
{
    //初始化udp
    AsyncUdpSocket *tempSocket=[[AsyncUdpSocket alloc] initIPv4];
    [tempSocket setDelegate:self];//这步很重要，否则无法自定义监听方法
    NSString *sendString = [NSString stringWithFormat:@"sRGB=%ld,%ld,%ld",(long)[redValue integerValue],(long)[greenValue integerValue],(long)[blueValue integerValue]];
    NSData *data =  [sendString dataUsingEncoding:NSUTF8StringEncoding];
    [tempSocket sendData: data toHost:@"192.168.4.1" port:1025 withTimeout:-1 tag:0];
}

@end
